﻿using System.Threading.Tasks;

using GameNetwork;
using GameNetwork.Interfaces;

namespace Menu.Screens.ConnectionScreen
{
    public class PlayerFinder
    {
        private readonly IMenuNetwork networkManager;

        private Task<bool> connectionTask;

        private readonly string playerName;

        public PlayerFinder(string playerName)
        {
            this.playerName = playerName;
            this.networkManager = NetworkDistributor.GetMenuNetwork();
        }

        public bool OpponentFound { get; private set; }

        public bool ConnectionFailed { get; private set; }

        public void Start()
        {
            this.connectionTask = new Task<bool>(this.StartRegistering);
            this.connectionTask.Start();
        }
        
        public PlayerFinderStateEnum EvaluateConnection()
        {
            if (!this.connectionTask.IsCompleted)
            {
                return PlayerFinderStateEnum.Connecting;
            }

            var result = this.connectionTask.Result;

            if (!result)
            {
                this.ConnectionFailed = true;
                return PlayerFinderStateEnum.Failure;
            }

            if (!this.networkManager.IsGameReadyToLoad)
            {
                return PlayerFinderStateEnum.WaitingForOpponent;
            }

            this.OpponentFound = true;
            return PlayerFinderStateEnum.OpponentFound;
        }

        public void CloseConnection()
        {
            this.networkManager.CancelRegistration();
        }

        private bool StartRegistering()
        {
            this.networkManager.SetupConnection();
            return this.networkManager.Register(this.playerName);
        }
    }
}